'use strict';

var _interopRequireDefault = require('@babel/runtime/helpers/interopRequireDefault');
var _interopRequireWildcard = require('@babel/runtime/helpers/interopRequireWildcard');
Object.defineProperty(exports, '__esModule', {
  value: true,
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(require('@babel/runtime/helpers/objectSpread2'));
var _toConsumableArray2 = _interopRequireDefault(
  require('@babel/runtime/helpers/toConsumableArray'),
);
var _slicedToArray2 = _interopRequireDefault(require('@babel/runtime/helpers/slicedToArray'));
var _objectWithoutProperties2 = _interopRequireDefault(
  require('@babel/runtime/helpers/objectWithoutProperties'),
);
var _react = _interopRequireWildcard(require('react'));
var _antd = require('antd');
var _createField = _interopRequireDefault(require('../../../createField'));
var _FieldContext = require('../../../contexts/FieldContext');
var _excluded = ['children', 'fieldNames', 'fetch', 'value', 'onChange'];
/**
 * 远程逐级拉取数据的级联下拉框，约定了 value 值为 CascaderOptionType[] 形式
 * @param props
 * @returns
 */
var LazyCascader = function LazyCascader(_ref) {
  var children = _ref.children,
    fieldNames = _ref.fieldNames,
    fetch = _ref.fetch,
    value = _ref.value,
    _onChange = _ref.onChange,
    props = (0, _objectWithoutProperties2.default)(_ref, _excluded);
  var _useFieldContext = (0, _FieldContext.useFieldContext)(),
    label = _useFieldContext.label;
  var _ref2 = fieldNames || {},
    _ref2$value = _ref2.value,
    valueKey = _ref2$value === void 0 ? 'value' : _ref2$value,
    _ref2$children = _ref2.children,
    childrenKey = _ref2$children === void 0 ? 'children' : _ref2$children;
  var _React$useState = _react.default.useState([]),
    _React$useState2 = (0, _slicedToArray2.default)(_React$useState, 2),
    options = _React$useState2[0],
    setOptions = _React$useState2[1];
  /**
   * 根据父节点拉取下一级数据
   */
  var loadData = (0, _react.useCallback)(
    function (selectedOptions) {
      var targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      fetch(targetOption).then(function (opts) {
        targetOption.loading = false;
        targetOption[childrenKey] = opts;
        setOptions((0, _toConsumableArray2.default)(options));
      });
    },
    [fetch, options],
  );
  /**
   * 获取第一级数据
   */
  (0, _react.useEffect)(
    function () {
      fetch().then(function (opts) {
        setOptions(opts);
      });
    },
    [fetch],
  );
  /**
   * 回显时，逐级拉取数据
   */
  (0, _react.useEffect)(
    function () {
      if (value && value.length && options && options.length) {
        var currentOptions = (0, _toConsumableArray2.default)(options);
        var currentOption = options.find(function (cp) {
          return cp[valueKey] === value[0][valueKey];
        });
        if (currentOption && !currentOption.children) {
          var fetchTasks = value.slice(0, value.length - 1).map(function (parent) {
            return {
              fn: fetch(parent),
            };
          });
          if (fetchTasks.length > 0) {
            Promise.all(
              fetchTasks.map(function (task) {
                return task.fn;
              }),
            ).then(function (allOpts) {
              allOpts.map(function (opts, idx) {
                if (!currentOption) return;
                currentOption[childrenKey] = opts;
                currentOption = currentOption.children.find(function (cp) {
                  return cp[valueKey] == value[idx + 1][valueKey];
                });
              });
              setOptions(currentOptions);
            });
          }
        }
      }
    },
    [options, value],
  );
  return (
    /*#__PURE__*/
    // @ts-ignore
    _react.default.createElement(
      _antd.Cascader,
      (0, _objectSpread2.default)(
        (0, _objectSpread2.default)(
          {
            placeholder: '\u8BF7\u9009\u62E9'.concat(label || ''),
          },
          props,
        ),
        {},
        {
          fieldNames: fieldNames,
          options: options,
          loadData: loadData,
          value: value
            ? value.map(function (item) {
                return item[valueKey];
              })
            : value,
          onChange: function onChange(value, selectedOptions) {
            if (_onChange) _onChange(selectedOptions);
          },
          changeOnSelect: true,
        },
      ),
      children,
    )
  );
};
var _default = (0, _createField.default)(LazyCascader, {
  defaultDetailType: 'text-for-options-value',
});
exports.default = _default;
